package org.example.backend.controller;

import org.example.backend.dto.Result;
import org.example.backend.util.ResponseUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 获取上传的图片文件
     * @param filename 文件名
     * @return 图片文件
     */
    @GetMapping("/image/{filename:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String filename) {
        try {
            // 尝试从文件系统获取资源
            String path = System.getProperty("user.dir");
            String filePath = path + "/backend/src/main/resources/static/upload/" + filename;
            File file = new File(filePath);
            
            System.out.println("请求图片: " + filename);
            System.out.println("查找路径: " + filePath);
            System.out.println("文件是否存在: " + file.exists());
            
            if (file.exists()) {
                Resource resource = new FileSystemResource(file);
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + file.getName() + "\"")
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(resource);
            }
            
            // 如果文件系统中不存在，尝试从classpath获取
            Resource resource = new ClassPathResource("static/upload/" + filename);
            System.out.println("Classpath资源是否存在: " + resource.exists());
            
            if (resource.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 列出所有上传的图片文件
     * @return 文件列表
     */
    @GetMapping("/list-images")
    public ResponseEntity<Result<List<Map<String, Object>>>> listImages() {
        try {
            String path = System.getProperty("user.dir");
            String uploadDir = path + "/backend/src/main/resources/static/upload/";
            File directory = new File(uploadDir);
            
            System.out.println("上传目录: " + uploadDir);
            System.out.println("目录是否存在: " + directory.exists());
            
            List<Map<String, Object>> files = new ArrayList<>();
            
            if (directory.exists() && directory.isDirectory()) {
                File[] fileList = directory.listFiles();
                if (fileList != null) {
                    for (File file : fileList) {
                        if (file.isFile()) {
                            Map<String, Object> fileInfo = new HashMap<>();
                            fileInfo.put("name", file.getName());
                            fileInfo.put("size", file.length());
                            fileInfo.put("path", "/upload/" + file.getName());
                            fileInfo.put("url", "/file/image/" + file.getName());
                            fileInfo.put("lastModified", file.lastModified());
                            files.add(fileInfo);
                        }
                    }
                }
            }
            
            return ResponseUtil.success(files);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("获取文件列表失败: " + e.getMessage());
        }
    }

    /**
     * 直接上传文件测试端点
     * @param file 文件
     * @return 上传结果
     */
    @PostMapping("/upload-test")
    public ResponseEntity<Result<Map<String, String>>> uploadTest(MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseUtil.badRequest("请选择文件");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            System.out.println("测试上传文件名: " + originalFilename);
            
            // 获取项目根目录
            String path = System.getProperty("user.dir");
            String uploadDir = path + "/backend/src/main/resources/static/upload/";
            
            // 确保目录存在
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            
            // 保存文件
            String filename = System.currentTimeMillis() + "_" + originalFilename;
            File dest = new File(uploadDir + filename);
            file.transferTo(dest);
            
            System.out.println("测试文件已保存至: " + dest.getAbsolutePath());
            System.out.println("测试文件是否存在: " + dest.exists() + ", 大小: " + dest.length());
            
            // 返回结果
            Map<String, String> result = new HashMap<>();
            result.put("filename", filename);
            result.put("url", "/upload/" + filename);
            result.put("fullPath", dest.getAbsolutePath());
            
            return ResponseUtil.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.serverError("测试上传失败: " + e.getMessage());
        }
    }
} 